package com.sscl.baselibrary.dialog

import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.viewbinding.ViewBinding
import com.sscl.baselibrary.R
import com.sscl.baselibrary.exts.getParameterizedType
import com.sscl.baselibrary.exts.saveAs

/**
 * BaseMvvmForViewBindingDialog
 *
 * MVVM模式下的ViewBinding对话框基类
 * @author jackie Penghe
 * @date 2025/9/10
 */
abstract class BaseMvvmForViewBindingDialog<VB : ViewBinding, VM : ViewModel> :
    BaseViewBindingDialog<VB>,
    ViewModelStoreOwner {

    protected val mViewModel: VM

    private val viewModelStoreRegistry = ViewModelStore()

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 构造方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


    constructor(context: Context) : this(context, R.style.FullScreenDialog)
    constructor(context: Context, theme: Int) : super(context, theme)
    constructor(
        context: Context,
        cancelable: Boolean,
        cancelListener: DialogInterface.OnCancelListener?
    ) : super(context, cancelable, cancelListener)

    init {
        val type = getParameterizedType()
        val vmClass: Class<VM> = type.actualTypeArguments[1].saveAs()
        mViewModel = ViewModelProvider(this)[vmClass]
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 重写参数
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    /**
     * The owned [ViewModelStore]
     */
    override val viewModelStore: ViewModelStore
        get() = viewModelStoreRegistry

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 重写方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    override fun initViewData(savedInstanceState: Bundle?) {
        initView(savedInstanceState)
        initViewModel()
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 抽象方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    abstract fun initView(savedInstanceState: Bundle?)

    abstract fun initViewModel()

}